
package com.scs.application.modules.upms.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.excel.handler.ExcelDictHandlerImpl;
import com.scs.application.core.exceptions.ExportException;
import com.scs.application.core.model.CommonResult;
import com.scs.application.core.model.PageResult;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.mvc.controller.ImAndExAbleController;
import com.scs.application.core.utils.DateUtils;
import com.scs.application.modules.upms.dto.SqlParseDTO;
import com.scs.application.modules.upms.entity.ReportConfig;
import com.scs.application.modules.upms.entity.ReportGridField;
import com.scs.application.modules.upms.request.ReportConfigQueryRequest;
import com.scs.application.modules.upms.service.ReportConfigService;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 报表配置 controller
 *
 */
@AllArgsConstructor
@RestController
@RequestMapping("/upms/report_configs")
public class ReportConfigController extends CrudController<ReportConfig, String, ReportConfigService> implements ImAndExAbleController<ReportConfigQueryRequest> {


    @GetMapping("/page")
    public PageResult page(ReportConfigQueryRequest request) {
        IPage page = service.page(request);
        return PageResult.ok("查询成功", page.getRecords(), page.getTotal());
    }

    @GetMapping("/list")
    public CommonResult list(ReportConfigQueryRequest request) {
        List<ReportConfig> list = service.list(request);
        return CommonResult.ok("查询成功", list);
    }


    @GetMapping("/{id}/fetch_data")
    public CommonResult fetchData(@PathVariable("id") String id, @RequestParam(required = false) Map<String, Object> params) {
        Map<String, Object> map = service.fetchData(id, params);
        return CommonResult.ok("查询成功", map);
    }


    @PostMapping("/sql_parse")
    public CommonResult sqlParse(@RequestBody SqlParseDTO dto) {
        List<Map<String, Object>> mapList = service.sqlParse(dto.getSql(), dto.getDatasourceId(), dto.getParams());
        return CommonResult.ok("解析成功", mapList);
    }

    @PostMapping("/{id}/copy")
    public CommonResult copy(@PathVariable("id") String id) {
        ReportConfig config = service.copy(id);
        return CommonResult.ok(config != null ? "复制成功" : "复制失败", config);
    }

    @GetMapping("/{id}/excel/export")
    public CommonResult excelExport(@PathVariable("id") String id, @RequestParam(required = false) Map<String, Object> params) {
        Map<String, Object> map = service.fetchData(id, false, params);

        ReportConfig config = (ReportConfig) map.get("config");
        List<ReportGridField> gridFields = (List<ReportGridField>) map.get("gridFields");
        List<Map> data = (List<Map>) map.get("data");

        String fileName = config.getName() + DateUtils.format(DateUtils.now(), DateUtils.YYYYMMDDHHMMSS_PATTER) + ".xlsx";

        ExportParams exportParams = new ExportParams(config.getName(), config.getName(), ExcelType.XSSF);
        exportParams.setDictHandler(ExcelDictHandlerImpl.getInstance());

        List<ExcelExportEntity> columnList = Lists.newArrayListWithExpectedSize(gridFields.size());
        for (ReportGridField field : gridFields) {
            if (!GlobalConsts.YES_STR.equals(field.getIsShow())) {
                continue;
            }
            ExcelExportEntity exportEntity = new ExcelExportEntity(field.getLabel(), field.getField());
            exportEntity.setDict(field.getDict());
            columnList.add(exportEntity);
        }

        try {
            setDownloadParam(fileName);

            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, columnList, data);
            workbook.write(response().getOutputStream());
            workbook.close();
        } catch (IOException e) {
            throw new ExportException("导出异常", e);
        }
        return CommonResult.ok("查询成功", map);
    }

    /**
     * 通过报表编码加载数据
     *
     * @param code   报表编码
     * @param params
     * @return
     */
    @GetMapping("/fetch_data")
    public CommonResult fetchDataByCode(@RequestParam("r_code") String code, @RequestParam(required = false) Map<String, Object> params) {
        ReportConfig config = service.getOne(Wrappers.<ReportConfig>query().eq("code", code).last("limit 1"));
        if (config == null) {
            return CommonResult.ok("查询失败，可能没有此报表配置信息");
        }
        Map<String, Object> map = service.fetchData(config.getId(), params);
        return CommonResult.ok("查询成功", map);
    }
}
